<template>
  <div class="app-container">
    <el-steps :active="active" finish-status="success" align-center>
      <el-step title="广告基本信息"></el-step>
      <el-step title="广告内容"></el-step>
    </el-steps>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row v-show="active == 1">
        <el-col :span="11">
          <el-form-item label="公司" prop="enterpriseId">
            <el-autocomplete
              style="width: 50%;"
              class="inline-input"
              v-model="form.enterpriseId"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              @select="handleSelect"
              clearable
            ></el-autocomplete>
          </el-form-item>
          <el-form-item style="width: 100%;" label="法人代表" prop="legalRepresentative">
            <el-input v-model="form.legalRepresentative" placeholder="请输入法人代表"/>
          </el-form-item>
          <el-form-item style="width: 100%;" label="联系电话" prop="contactPhone">
            <el-input style="width: 100%;" v-model="form.contactPhone" placeholder="请输入联系电话"/>
          </el-form-item>
          <el-form-item style="width: 100%;" label="电子邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入电子邮箱"/>
          </el-form-item>
          <el-form-item label="费用" prop="cost" style="width: 50%">
            <el-input v-model="form.cost" placeholder="请输入费用">
              <div slot="append">万元</div>
            </el-input>
          </el-form-item>
          <el-form-item label="广告类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择广告类型">
              <el-option
                v-for="dict in dict.type.village_advertisements_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="投放时间" prop="startTime">
            <el-date-picker clearable
                            style="width: 35%;"
                            v-model="form.startTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择投放时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker clearable
                            style="width: 35%;"
                            v-model="form.endTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择结束时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item style="width: 100%;" label="推广目的" prop="promotionGoal">
            <el-input v-model="form.promotionGoal" type="textarea" placeholder="请输入内容"/>
          </el-form-item>
        </el-col>
        <el-col :span="2" style="height: 570px;display: flex;justify-content: center">
          <div style="height: 100%;width: 2px;background-color: #d9d9d9"></div>
        </el-col>
        <el-col :span="11">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in dict.type.aillage_advertising_status"
                :key="dict.value"
                :label="parseInt(dict.value)"
              >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item style="width: 100%;" label="官网地址" prop="officialWebsite">
            <el-input v-model="form.officialWebsite" placeholder="请输入官网地址"/>
          </el-form-item>
          <el-form-item label="封面" prop="contentImageUrl">
            <image-upload :limit="1" v-model="form.contentImageUrl"/>
          </el-form-item>
          <el-form-item label="轮播图片" prop="carouselImages">
            <image-upload :limit="3" v-model="form.carouselImages"/>
          </el-form-item>

        </el-col>
      </el-row>
      <el-row v-show="active == 2">
        <el-col :span="24">
          <div style="margin-bottom: 20px;text-align: right;">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>


          <el-form-item style="width: 80%;" label="简介" prop="introduction">
            <el-input v-model="form.introduction" type="textarea" placeholder="请输入内容"/>
          </el-form-item>

          <el-form-item label="广告内容" prop="content">
            <editor v-model="form.content" :min-height="192"/>
          </el-form-item>

        </el-col>
      </el-row>
      <div style="display: flex;justify-content: space-evenly">
        <el-button style="margin-top: 12px;width: 200px" type="primary" plain @click="lastStep"
                   :disabled="active === 1"
        >
          上一步
        </el-button>
        <el-button style="margin-top: 12px;width: 200px" type="primary" plain @click="next" :disabled="active === 2">
          下一步
        </el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
import {
  listAdvertisements,
  getAdvertisements,
  delAdvertisements,
  addAdvertisements,
  updateAdvertisements
} from '@/api/village/advertisements'
import {
  noListEnterprise

} from '@/api/village/enterprise'

export default {
  name: 'Advertisements',
  dicts: ['village_advertisements_type', 'aillage_advertising_status'],
  data() {
    return {

      expenselist: [],
      restaurants: [],
      state1: '',
      active: 1,
      options: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 广告信息管理表格数据
      advertisementsList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        company: null,
        contactPhone: null,
        status: null,
        type: null,
        startTime: null,
        endTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        enterpriseId: [
          { required: true, message: '公司不能为空', trigger: 'blur' }
        ],
        legalRepresentative: [
          { required: true, message: '法人代表不能为空', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '负责人电话不能为空', trigger: 'blur' },
          {
            pattern: /^1[3-9]\d{9}|^(\+\d{1,4})?[-\s]?(\(?\d{1,4}\)?[-\s]?)?\d{1,4}[-\s]?\d{1,4}([-\s]?\d{1,9})?$/,
            message: '请输入正确的电话号码（支持手机号和座机）',
            trigger: 'blur'
          }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'change' },
          {
            pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
            message: '请输入有效的邮箱地址',
            trigger: 'blur'
          }
        ],
        cost: [
          { required: true, message: '费用不能为空', trigger: 'blur' },
          {
            pattern: /^\d+(\.\d{1,3})?$/,
            message: '经费应为最多三位小数的数字',
            trigger: 'blur'
          }
        ],
        type: [
          { required: true, message: '广告类型不能为空', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '投放时间不能为空', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '结束时间不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '广告内容不能为空', trigger: 'blur' }
        ],
        contentImageUrl: [
          { required: true, message: '封面不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    if (this.$route.query.id != null) {
      this.handleUpdate(this.$route.query)
    }
    this.restaurants = this.loadAll()

  },
  methods: {
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },

    loadAll() {
      return []
    },
    handleSelect(item) {
      console.log(item)
    },

    next() {
      if (this.active++ > 1) this.active = 1
    },
    lastStep() {
      if (this.active-- < 0) this.active = 2
    },
    /** 查询广告信息管理列表 */
    getList() {
      this.loading = true
      listAdvertisements(this.queryParams).then(response => {
        this.advertisementsList = response.rows
        this.total = response.total
        this.loading = false
      })
      noListEnterprise(this.queryParams).then(response => {
        console.log(response.rows)
        this.options = response.rows.map(item => {
          return {
            value: item.name,
            label: item.name
          }
        })
        this.expenselist = response.rows.map(item => {
          return {
            value: item.id,
            label: item.name
          }
        })
        console.log('查询广告信息管理列表', this.options)

        this.restaurants = this.options

      })
    },
    // 取消按钮
    cancel() {
      this.reset()
      this.$router.push('/advertisements')
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        company: null,
        legalRepresentative: null,
        contactPhone: null,
        email: null,
        status: null,
        cost: null,
        promotionGoal: null,
        type: null,
        startTime: null,
        endTime: null,
        carouselImages: null,
        introduction: null,
        content: null,
        contentImageUrl: null,
        createdTime: null,
        updatedTime: null,
        createdBy: null,
        updatedBy: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加广告信息管理'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getAdvertisements(id).then(response => {
        this.form = response.data
      })
    },
    /** 提交按钮 */
    submitForm() {
      console.log('提交按钮', this.form.officialWebsite)
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateAdvertisements(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.$router.push('/advertisements')
            })
          } else {
            addAdvertisements(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.$router.push('/advertisements')
            })
          }
        }else
        {
          this.$modal.msgError('必要数据未填写')
        }
      }

    )
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除广告信息管理编号为"' + ids + '"的数据项？').then(function() {
        return delAdvertisements(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('village/advertisements/export', {
        ...this.queryParams
      }, `advertisements_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>

</style>
